package android.homeaccount;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.homeaccount.R;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Login extends Activity
{	
	EditText etUsername;
	EditText etPassword;
	
	final static int RESULT_Back = 20;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login);
        
        Intent i = new Intent(Login.this, Login1.class);
        startActivityForResult(i, 0);

        //TextView tvUsername = (TextView) findViewById(R.id.tvUsername);
        //TextView tvPassword = (TextView) findViewById(R.id.tvPassword);
        etUsername = (EditText) findViewById(R.id.etUsername);
        etPassword = (EditText) findViewById(R.id.etPassword);
        Button btLogin = (Button) findViewById(R.id.btLogin);
        Button btClear = (Button) findViewById(R.id.btClear);
        Button btExit = (Button) findViewById(R.id.btExit);

        btLogin.setOnClickListener(new OnClickListener()
        {
			@Override
			public void onClick(View v)
			{
				String _username = etUsername.getText().toString();
				String _password = etPassword.getText().toString();

				// TODO Auto-generated method stub
				if(_username.equals("") || _password.equals(""))
				{
					AlertDialog.Builder dialog = new AlertDialog.Builder(v.getContext());
					dialog.setTitle("Error Massage");
					dialog.setMessage("�?ุณยั�?�?ม�?�?ด�?�?ส�? Username หรือ Password");
					dialog.setNeutralButton("Close", new DialogInterface.OnClickListener()
					{
						@Override
						public void onClick(DialogInterface arg0, int arg1)
						{
							// TODO Auto-generated method stub
						}
					});
					dialog.show();
				}
				else
				{	
//					Intent i = new Intent(Login.this, Menu.class);
//					startActivity(i);
					
					HttpClient httpclient = new DefaultHttpClient();
//			        HttpPost httppost = new HttpPost("http://203.158.130.111/debug/app/login_check.php");
			        
					HttpPost httppost = new HttpPost("http://10.10.92.44/php/homeaccount_v3/ext/login_check.php");
			        
			        //HttpPost httppost = new HttpPost("http://localhost/homeaccount_ci173/index.php/member/mainprofile");
			        //HttpPost httppost = new HttpPost("http://homeaccount.monofocus.in.th/index.php/member/authentication");
					try
					{
						List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();

						nameValuePairs.add(new BasicNameValuePair("email", _username));
						nameValuePairs.add(new BasicNameValuePair("password", _password));

						httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

						HttpResponse response = httpclient.execute(httppost);
						String responseText = EntityUtils.toString(response.getEntity());

						//Toast.makeText(getBaseContext(), responseText, Toast.LENGTH_LONG).show();
						String success = "Logined";
						//String success = "Error!!";

			            if(success.equals(responseText))
			            {
			            	Log.i("Login success", "Usrename and Password is correct");

			            	Intent myIntent = new Intent(Login.this, Menu.class);
			            	Bundle bundle = new Bundle();
		                    bundle.putString("USERNAME", _username);
		                    myIntent.putExtras(bundle);
			            	startActivityForResult(myIntent, 0);
			            }
			            else
			            {
			            	final String title = getString(R.string.login_failed_title);
			                final String message = getString(R.string.login_failed_message);
			                showCloseDialogBox(title, message);
			                Log.i("Login Failed", "Username/Password not correct");
			            }
					}
					catch(Exception e)
					{
						Log.i("Response", "Can't connect to the server");

						//Toast.makeText(getBaseContext(), "Can't connect to the server", Toast.LENGTH_LONG).show();

						AlertDialog.Builder dialog = new AlertDialog.Builder(v.getContext());
						dialog.setTitle("Connection Error");
						dialog.setMessage("Can't connect to the server");
						dialog.setNeutralButton("Close", new DialogInterface.OnClickListener()
						{
							@Override
							public void onClick(DialogInterface arg0, int arg1)
							{
								// TODO Auto-generated method stub
							}
						});
						dialog.show();
					}
				}
			}
        });
        btClear.setOnClickListener(new OnClickListener()
        {
			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				etUsername.setText("");
				etPassword.setText("");
			}
        });
        
        btExit.setOnClickListener(new OnClickListener()
        {
			@Override
			public void onClick(View v)
			{
				// TODO Auto-generated method stub
				final String title = getString(R.string.exit_title);
                final String message = getString(R.string.exit_message);
				showYesNoDialogBox(title, message);
			}
        });
    }

    private void showCloseDialogBox(final String title, final String message)
    {
        Builder setupAlert;
        setupAlert = new AlertDialog.Builder(this).setTitle(title).setMessage(message).setNegativeButton("Close", new DialogInterface.OnClickListener()
        {
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				// TODO Auto-generated method stub
			}
        });
        setupAlert.show();
    }
    
    private void showYesNoDialogBox(final String title, final String message)
    {
        Builder setupAlert;
        setupAlert = new AlertDialog.Builder(this).setTitle(title).setMessage(message)
        .setPositiveButton("Yes",new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int whichButton)
            {
            	Intent intent = new Intent(Intent.ACTION_MAIN);
				intent.addCategory(Intent.CATEGORY_HOME);
				intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				startActivity(intent);
            }
        })
        .setNegativeButton("No", new DialogInterface.OnClickListener()
        {
            public void onClick(DialogInterface dialog, int whichButton)
            {
                // just do nothing
            }
        });
        setupAlert.show();
    }
    
    protected void onActivityResult(int requestCode, int resultCode, Intent intent)
    {
		super.onActivityResult(requestCode, resultCode, intent);
		if(resultCode == Login.RESULT_Back)
		{	
			etUsername.setText("");
			etPassword.setText("");
		}
	}
}